<template>
  <div class="canton-fair-purchasers-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader />
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu />
      
      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('canton.purchaser.search.title') }}</div>
          
          <!-- 搜索输入区 -->
          <div class="search-box-container">
            <div class="search-fields-row">
              <!-- 采购商名称搜索框 -->
              <div class="search-field">
<!--                <div class="search-field-label">{{ t('canton.purchaser.search.name.session.label') }}</div>-->
                <el-input
                  v-model="searchKeyword"
                  :placeholder="t('canton.purchaser.search.name.placeholder')"
                  clearable
                  class="search-input"
                  @clear="resetNameSearch"
                  @keyup.enter="handleSearch"
                  prefix-icon="el-icon-search"
                >
                </el-input>
              </div>
              
              <!-- 产品类型搜索框 -->
              <div class="search-field">
<!--                <div class="search-field-label">{{ t('canton.purchaser.search.product.type.label') }}</div>-->
                <el-input
                  v-model="productTypeKeyword"
                  :placeholder="t('canton.purchaser.search.product.type.placeholder')"
                  clearable
                  class="search-input"
                  @clear="resetProductTypeSearch"
                  @keyup.enter="handleSearch"
                  prefix-icon="el-icon-search"
                >
                </el-input>
              </div>
            </div>

          </div>
        </div>
        
        <!-- 主内容区域 -->
        <div class="purchasers-main">
          <!-- 左侧筛选器 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters" class="reset-filter-btn">
                  {{ t('canton.purchaser.reset.filters') }}
                </el-button>
              </div>
              
              <!-- 广交会届数筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.sessionInfo }">
                <div class="filter-header" @click="toggleFilter('sessionInfo')">
                  <span>{{ t('canton.purchaser.session') }}</span>
                  <i :class="['el-icon', expanded.sessionInfo ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.sessionInfo" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search">
                    <el-input 
                      v-model="sessionInfoSearch" 
                      :placeholder="t('canton.purchaser.session.placeholder')" 
                      size="small" 
                      clearable
                      prefix-icon="el-icon-search"
                    ></el-input>
                  </div>
                  
                  <el-checkbox :indeterminate="isIndeterminate.sessionInfo" v-model="checkAll.sessionInfo" @change="handleCheckAllChange('sessionInfo')">{{ t('canton.purchaser.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.sessionInfo" @change="handleFilterChange('sessionInfo')">
                    <el-checkbox v-for="item in filteredSessionInfos"
                      :key="item" 
                      :value="item">
                      {{ item }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              
              <!-- 国家筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.country }">
                <div class="filter-header" @click="toggleFilter('country')">
                  <span>{{ t('canton.purchaser.country') }}</span>
                  <i :class="['el-icon', expanded.country ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.country" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search">
                    <el-input 
                      v-model="countrySearch" 
                      :placeholder="t('canton.purchaser.country.placeholder')" 
                      size="small" 
                      clearable
                      prefix-icon="el-icon-search"
                    ></el-input>
                  </div>
                  
                  <el-checkbox :indeterminate="isIndeterminate.country" v-model="checkAll.country" @change="handleCheckAllChange('country')">{{ t('canton.purchaser.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.country" @change="handleFilterChange('country')">
                    <el-checkbox v-for="item in filteredCountries"
                      :key="item" 
                      :value="item">
                      {{ item }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group" :class="{ expanded: expanded.contact }">
                <div class="filter-header" @click="toggleFilter('contact')">
                  <span>{{ t('canton.purchaser.filter.contact') }}</span>
                  <i :class="['el-icon', expanded.contact ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.contact" class="filter-content">
                  <el-checkbox-group v-model="filters.contact" @change="handleContactChange">
                    <el-checkbox value="phone">{{ t('canton.purchaser.filter.contact.phone') }}</el-checkbox>
                    <el-checkbox value="fax">{{ t('canton.purchaser.filter.contact.fax') }}</el-checkbox>
                    <el-checkbox value="email">{{ t('canton.purchaser.filter.contact.email') }}</el-checkbox>
                    <el-checkbox value="website">{{ t('canton.purchaser.filter.contact.website') }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 导出数据模块 -->
            <div class="export-module">
              <div class="export-info">
                <span>{{ t('canton.purchaser.matching.records') }}: </span>
                <span class="export-count">{{ total >= 10000 ? '10,000+' : total }}</span>
              </div>
              <el-button @click="exportData" class="export-module-btn" type="primary" :loading="exportLoading">
                  <el-icon><Download /></el-icon>
                  {{ t('canton.purchaser.export.data') }}
                </el-button>
            </div>
            
            <!-- 采购商列表 -->
            <div v-loading="loading" class="purchaser-card-list">
              <!-- 无数据提示 -->
              <div v-if="!loading && purchasers.length === 0" class="no-data">
                <i class="el-icon-warning-outline"></i>
                <p>{{ t('canton.purchaser.no.data') }}</p>
              </div>
              
              <!-- 骨架屏 -->
              <div v-if="loading && purchasers.length === 0" class="skeleton-loading">
                <div v-for="i in 6" :key="i" class="skeleton-card">
                  <div class="skeleton-header">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-title"></div>
                  </div>
                  <div class="skeleton-content">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                  </div>
                </div>
              </div>
              
              <!-- 采购商卡片 -->
              <div 
                v-for="(purchaser, index) in paginatedPurchasers" 
                :key="index" 
                class="purchaser-card"
              >
                <!-- 卡片头部 - 显示公司名称 -->
                <div class="card-header">
                  <div class="company-info">
                    <div class="company-avatar">
                      <img 
                        :src="getAvatarUrl(purchaser.companyName)" 
                        class="cartoon-avatar" 
                        :alt="purchaser.companyName"
                        @error="handleAvatarError"
                      />
                    </div>
                    <div class="company-name">{{ purchaser.companyName || '' }}</div>
                  </div>
                </div>
                
                <!-- 分隔线 -->
                <div class="card-divider"></div>
                
                <!-- 基本信息和详情按钮并排显示 -->
                <div class="info-button-container">
                  <!-- 基本信息区域 -->
                  <div class="card-basic-info">
                    <div class="basic-info-grid">
                      <div class="info-row" v-if="purchaser.sessionInfo">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.purchaser.session.info') }}</span>
                          <span class="info-value">{{ purchaser.sessionInfo }}</span>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.purchaser.country.info') }}</span>
                          <span class="info-value">
                            <img v-if="getCountryFlag(purchaser.country || purchaser.countryRegion)" 
                                :src="getCountryFlag(purchaser.country || purchaser.countryRegion)" 
                                class="country-flag" 
                                @error="handleFlagError" />
                            {{ purchaser.country || purchaser.countryRegion || '-' }}
                          </span>
                        </div>
                      </div>
                      <div class="info-row" v-if="purchaser.procurementProductType">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.purchaser.product.type') }}</span>
                          <span class="info-value">{{ purchaser.procurementProductType }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 详情按钮 -->
                  <div class="detail-button-container">
                    <el-button @click="togglePurchaserDetails(purchaser)" class="detail-btn">
                      {{ purchaser.expanded ? t('canton.purchaser.collapse') : t('canton.purchaser.details') }}
                    </el-button>
                  </div>
                </div>
                
                <!-- 详细内容 - 点击详情后显示 -->
                <div class="card-content" v-show="purchaser.expanded">
                  <div class="detail-title">{{ t('canton.purchaser.detail.title') }}</div>
                  <!-- 采购商详细信息 -->
                  <div class="info-table-wrapper">
                    <table class="info-table">
                      <tbody>
                        <tr v-if="purchaser.contactPerson">
                          <td class="label-cell">{{ t('canton.purchaser.contact.person') }}</td>
                          <td class="value-cell" colspan="3">{{ purchaser.contactPerson }}</td>
                        </tr>
                        <tr v-if="purchaser.contactWay">
                          <td class="label-cell">{{ t('canton.purchaser.contact.way') }}</td>
                          <td class="value-cell" colspan="3">{{ purchaser.contactWay }}</td>
                        </tr>
                        <tr v-if="purchaser.phone">
                          <td class="label-cell">{{ t('canton.purchaser.phone') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="purchaser.phone && purchaser.phone.includes('*')"
                              :content="t('canton.purchaser.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(purchaser, 'phone')">
                                {{ purchaser.phone }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ purchaser.phone }}</span>
                          </td>
                        </tr>
                        <tr v-if="purchaser.fax">
                          <td class="label-cell">{{ t('canton.purchaser.fax') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="purchaser.fax && purchaser.fax.includes('*')"
                              :content="t('canton.purchaser.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(purchaser, 'fax')">
                                {{ purchaser.fax }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ purchaser.fax }}</span>
                          </td>
                        </tr>
                        <tr v-if="purchaser.address">
                          <td class="label-cell">{{ t('canton.purchaser.address') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                                v-if="purchaser.address && purchaser.address.includes('*')"
                                :content="t('canton.purchaser.view.full.contact.tooltip')"
                                placement="top"
                                effect="dark"
                            >
                              <span
                                  class="masked-info"
                                  @click="showFullContactInfo(purchaser, 'address')">
                                {{ purchaser.address }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ purchaser.address }}</span>
                          </td>
                        </tr>
                        <tr v-if="purchaser.zipCode">
                          <td class="label-cell">{{ t('canton.purchaser.zipcode') }}</td>
                          <td class="value-cell" colspan="3">{{ purchaser.zipCode }}</td>
                        </tr>
                        <tr v-if="purchaser.email">
                          <td class="label-cell">{{ t('canton.purchaser.email') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="purchaser.email && purchaser.email.includes('*')"
                              :content="t('canton.purchaser.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(purchaser, 'email')">
                                {{ purchaser.email }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ purchaser.email }}</span>
                          </td>
                        </tr>
                        <tr v-if="purchaser.website">
                          <td class="label-cell">{{ t('canton.purchaser.website') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="purchaser.website && purchaser.website.includes('*')"
                              :content="t('canton.purchaser.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(purchaser, 'website')">
                                {{ purchaser.website }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>
                              <a :href="addHttpPrefix(purchaser.website)" target="_blank">{{ purchaser.website }}</a>
                            </span>
                          </td>
                        </tr>
                        <!-- 动态显示其他扩展字段 -->
                        <template v-for="(value, key) in getOtherExtendedFields(purchaser)" :key="key">
                          <tr v-if="value">
                            <td class="label-cell">{{ getFieldLabel(key) }}</td>
                            <td class="value-cell" colspan="3">
                              <template v-if="shouldRenderHtml(key, value)">
                                <span v-html="value"></span>
                              </template>
                              <template v-else-if="isMaskedInfo(key, value)">
                                <el-tooltip
                                  :content="t('canton.purchaser.view.full.contact.tooltip')"
                                  placement="top"
                                  effect="dark"
                                >
                                  <span
                                    class="masked-info"
                                    @click="showFullContactInfo(purchaser, normalizeFieldKey(key))"
                                  >
                                    {{ value }}
                                    <el-icon class="info-lock-icon"><Lock /></el-icon>
                                  </span>
                                </el-tooltip>
                              </template>
                              <template v-else>
                                <span>{{ value }}</span>
                              </template>
                            </td>
                          </tr>
                        </template>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="sizes, prev, pager, next, jumper"
                :total="Math.min(Math.max(total, 1), 10000)"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
                :pager-count="7"
                :disabled="loading"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 导出对话框 -->
  <el-dialog
    v-model="exportDialogVisible"
    :title="t('export.dialog.title')"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('export.matching.records') }}: <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>{{ t('export.current.balance') }}: <span class="export-highlight">{{ userBalance.exportQuotaRemaining || 0 }}</span></p>
        <p class="export-note">{{ t('export.note') }}</p>
        <p class="export-limit-notice">{{ t('export.max.limit.notice') }}</p>
      </div>

      <!-- 字段选择区域 -->
      <div class="field-selection">
        <div class="field-selection-header">
          <h4>{{ t('export.selectFields') }}</h4>
          <div class="field-selection-actions">
            <el-button
              size="small"
              @click="selectAllFields"
              :disabled="isAllFieldsSelected"
            >
              {{ t('export.selectAll') }}
            </el-button>
            <el-button
              size="small"
              @click="selectNoFields"
              :disabled="isNoFieldsSelected"
            >
              {{ t('export.selectNone') }}
            </el-button>
          </div>
        </div>

        <div class="field-selection-content">
          <div class="field-grid">
            <div
              v-for="field in allFields"
              :key="field.key"
              class="field-item"
            >
              <el-checkbox
                v-model="field.selected"
                @change="updateSelectedFields"
              >
                <span :class="{ 'field-unselected': !field.selected }">
                  {{ t(field.labelKey) }}
                </span>
              </el-checkbox>
            </div>
          </div>

          <div v-if="isNoFieldsSelected" class="field-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.noFieldsSelected') }}
          </div>
        </div>
      </div>

      <div class="export-input">
        <p>{{ t('export.enter.count') }}</p>
        <el-input-number
          v-model="exportCount"
          :min="1"
          :max="Math.max(1, Math.min(totalMatchCount, 50000, userBalance.exportQuotaRemaining || 1))"
          :step="100"
          size="large"
          controls-position="right"
        />

        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.exceed') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.balance') }}
          </p>
          <p v-if="isExportLimitExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.limit') }}
          </p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('export.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="doExport"
          :loading="exportLoading"
          :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount || selectedFields.length === 0"
        >
          {{ t('export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElDialog, ElInput, ElInputNumber } from 'element-plus'
import { Download, Lock } from '@element-plus/icons-vue'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { getCantonFairPurchasers, exportCantonFairPurchasers, getCantonFairPurchasersCount, getUserBalanceInfo, getPurchaserFullContactInfo } from '@/api/purchasers'
import { t as tRaw, getCurrentLanguage, addTranslation, currentLanguage as globalCurrentLanguage } from '@/utils/i18n'  // 导入t, getCurrentLanguage, and addTranslation functions

export default {
  name: 'CantonFairPurchasers',
  components: {
    MainHeader,
    SideMenu,
    Download,
    Lock
  },
  setup() {
    // 国家名称中英文映射表
    const COUNTRY_TRANSLATIONS = {
      '中国': 'China',
      '美国': 'USA',
      '日本': 'Japan',
      '英国': 'United Kingdom',
      '德国': 'Germany',
      '法国': 'France',
      '加拿大': 'Canada',
      '澳大利亚': 'Australia',
      '印度': 'India',
      '巴西': 'Brazil',
      '俄罗斯': 'Russia',
      '韩国': 'South Korea',
      '意大利': 'Italy',
      '西班牙': 'Spain',
      '墨西哥': 'Mexico',
      '印度尼西亚': 'Indonesia',
      '荷兰': 'Netherlands',
      '沙特阿拉伯': 'Saudi Arabia',
      '瑞士': 'Switzerland',
      '土耳其': 'Turkey',
      '台湾': 'Taiwan',
      '瑞典': 'Sweden',
      '波兰': 'Poland',
      '比利时': 'Belgium',
      '泰国': 'Thailand',
      '爱尔兰': 'Ireland',
      '奥地利': 'Austria',
      '挪威': 'Norway',
      '阿联酋': 'United Arab Emirates',
      '以色列': 'Israel',
      '丹麦': 'Denmark',
      '新加坡': 'Singapore',
      '马来西亚': 'Malaysia',
      '中国香港': 'Hong Kong',
      '菲律宾': 'Philippines',
      '越南': 'Vietnam',
      '孟加拉国': 'Bangladesh',
      '伊朗': 'Iran',
      '阿尔巴尼亚': 'Albania',
      '保加利亚': 'Bulgaria',
      '捷克': 'Czech Republic',
      '斯洛伐克': 'Slovakia',
      '乌克兰': 'Ukraine',
      '白俄罗斯': 'Belarus',
      '希腊': 'Greece',
      '匈牙利': 'Hungary',
      '冰岛': 'Iceland',
      // '中国香港': 'Hongkong',
      '加纳': 'Ghana'
    };
    
    // 英文到中文的反向映射
    const REVERSE_COUNTRY_TRANSLATIONS = {};
    for (const [zhName, enName] of Object.entries(COUNTRY_TRANSLATIONS)) {
      REVERSE_COUNTRY_TRANSLATIONS[enName] = zhName;
    }
    
    const loading = ref(false)
    const exportLoading = ref(false)
    const purchasers = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const searchKeyword = ref('')
    const productTypeKeyword = ref('')
    
    // 筛选器展开状态
    const expanded = reactive({
      sessionInfo: true,
      country: true,
      contact: true
    })
    
    // 筛选条件
    const filters = reactive({
      sessionInfo: [],
      country: [],
      contact: []
    })
    
    // 全选状态
    const checkAll = reactive({
      sessionInfo: false,
      country: false
    })
    
    // 是否半选状态
    const isIndeterminate = reactive({
      sessionInfo: false,
      country: false
    })
    
    // 筛选器搜索关键词
    const sessionInfoSearch = ref('')
    const countrySearch = ref('')
    
    // 筛选后的广交会届数
    const filteredSessionInfos = computed(() => {
      // 从采购商数据中提取不重复的届数
      const sessions = [...new Set(purchasers.value.map(item => item.sessionInfo).filter(Boolean))];

      // 添加静态的届数选项，只包含实际存在的数据表对应的届数
      const additionalSessions = [
        '第125届','第126届','第127届', '第129届', '第130届', '第131届', '第132届', '第133届', '第134届', '第135届', '第136届', '第137届'
      ].filter(session => !sessions.includes(session));
      
      // 合并并按届数排序
      const allSessions = [...sessions, ...additionalSessions].sort((a, b) => {
        // 从字符串中提取数字进行比较
        const numA = parseInt(a.match(/\d+/)) || 0;
        const numB = parseInt(b.match(/\d+/)) || 0;
        return numB - numA; // 降序排列，最新届数在前
      });
      
      // 搜索过滤
      if (!sessionInfoSearch.value) return allSessions;
      return allSessions.filter(session => 
        session.toLowerCase().includes(sessionInfoSearch.value.toLowerCase())
      );
    })
    
    // 筛选后的国家列表
    const filteredCountries = computed(() => {
      // 从采购商数据中提取不重复的国家
      const countries = [...new Set(purchasers.value.map(item => item.country || item.countryRegion).filter(Boolean))];
      
      // 添加静态的国家选项
      const additionalCountries = [
        'USA', 'China', 'Japan', 'United Kingdom', 'Germany', 'France', 'Canada', 'Australia',
        'India', 'Brazil', 'Russia', 'South Korea', 'Italy', 'Spain', 'Mexico', 'Indonesia',
        'Netherlands', 'Saudi Arabia', 'Switzerland', 'Turkey', 'Taiwan', 'Sweden', 'Poland',
        'Belgium', 'Thailand', 'Ireland', 'Austria', 'Norway', 'United Arab Emirates', 'Israel',
        'Denmark', 'Singapore', 'Malaysia', 'Hong Kong', 'Philippines', 'Vietnam'
      ].filter(country => !countries.includes(country));
      
      // 合并数组，确保实际数据在前
      const allCountries = [...countries, ...additionalCountries];
      // 注意：搜索过滤在 localizedCountries 中按本地化后的展示名进行
      return allCountries;
    })
    
    // 筛选后的广交会届数（国际化版本）
    const localizedSessionInfos = computed(() => {
      // 获取当前语言
      const currentLang = getCurrentLanguage();
      
      // 如果是英文，需要将中文届数转为英文
      if (currentLang === 'en') {
        return filteredSessionInfos.value.map(session => {
          // 提取届数数字
          const match = session.match(/\d+/);
          const sessionNumber = match ? match[0] : '';
          
          if (sessionNumber) {
            // 返回英文格式的届数
            return `Canton Fair ${sessionNumber}th Session`;
          }
          return session; // 无法转换的保持原样
        });
      }
      
      // 中文保持原样
      return filteredSessionInfos.value;
    });
    
    // 筛选后的国家列表（国际化版本）
    const localizedCountries = computed(() => {
      const currentLang = getCurrentLanguage();
      // 1) 先按当前语言把候选列表做本地化转换
      let mapped = filteredCountries.value.map(country => {
        if (currentLang === 'en') {
          return COUNTRY_TRANSLATIONS[country] || country;
        } else if (currentLang === 'zh') {
          return REVERSE_COUNTRY_TRANSLATIONS[country] || country;
        }
        return country;
      });

      // 2) 在本地化后的显示名上执行搜索过滤
      if (countrySearch.value) {
        const kw = countrySearch.value.toLowerCase();
        mapped = mapped.filter(name => String(name).toLowerCase().includes(kw));
      }

      // 3) 确保已选中的国家始终出现在可选项中
      const selected = Array.isArray(filters.country) ? filters.country : [];
      const merged = Array.from(new Set([...(mapped || []), ...selected]));
      return merged;
    });
    
    // 切换筛选器展开状态
    const toggleFilter = (filter) => {
      expanded[filter] = !expanded[filter];
    }
    
    // 处理全选/取消全选
    const handleCheckAllChange = (field) => {
      if (checkAll[field]) {
        // 全选
        const options = getOptionsForField(field);
        filters[field] = [...options];
      } else {
        // 取消全选
        filters[field] = [];
      }
      isIndeterminate[field] = false;
      
      // 重新获取数据
      currentPage.value = 1; // 重置到第一页
      fetchPurchasers();
    }
    
    // 处理筛选条件变化
    const handleFilterChange = (field) => {
      const options = getOptionsForField(field);
      
      if (filters[field].length === 0) {
        checkAll[field] = false;
        isIndeterminate[field] = false;
      } else if (filters[field].length === options.length) {
        checkAll[field] = true;
        isIndeterminate[field] = false;
      } else {
        checkAll[field] = false;
        isIndeterminate[field] = true;
      }
      
      // 重新获取数据
      currentPage.value = 1; // 重置到第一页
      fetchPurchasers();
    }

    const handleContactChange = () => {
      currentPage.value = 1;
      fetchPurchasers();
    };
    
    // 重置所有筛选条件
    const resetAllFilters = () => {
      // 重置所有筛选条件
      Object.keys(filters).forEach(key => {
        filters[key] = [];
        checkAll[key] = false;
        isIndeterminate[key] = false;
      });
      
      // 重置搜索关键词
      searchKeyword.value = '';
      productTypeKeyword.value = '';
      sessionInfoSearch.value = '';
      countrySearch.value = '';
      
      currentPage.value = 1; // 重置到第一页
      fetchPurchasers();
    }
    
    // 获取特定字段的所有选项
    const getOptionsForField = (field) => {
      switch (field) {
        case 'sessionInfo':
          return localizedSessionInfos.value;
        case 'country':
          return localizedCountries.value;
        default:
          return [];
      }
    }
    
    // 导出相关的状态
    const exportDialogVisible = ref(false)
    const totalMatchCount = ref(0)
    const exportCount = ref(0)
    const userBalance = ref({
      exportQuotaRemaining: 0
    })
    const isExportCountExceeded = computed(() => {
      return exportCount.value > totalMatchCount.value
    })
    const isBalanceInsufficient = computed(() => {
      return exportCount.value > userBalance.value.exportQuotaRemaining
    })
    const isExportLimitExceeded = computed(() => {
      return exportCount.value > 50000
    })

    // 字段选择相关变量
    const selectedFields = ref([]);
    // 使用全局响应式语言变量，确保语言切换时实时更新
    const currentLanguage = globalCurrentLanguage;
    // 本地t包装，确保模板中拿到的是函数
    const t = (key, params) => {
      try { return typeof tRaw === 'function' ? tRaw(key, params) : (tRaw && typeof tRaw.t === 'function' ? tRaw.t(key, params) : key) }
      catch { return key }
    }

    // 创建国际化字段配置
    const createFieldsConfig = () => {
      return [
        { key: 'companyName', labelKey: 'purchaser.field.companyName', selected: true },
        { key: 'country', labelKey: 'purchaser.field.country', selected: true },
        { key: 'extendedFields.procurementProductType', labelKey: 'purchaser.field.procurementProductType', selected: true },
        { key: 'contactPerson', labelKey: 'purchaser.field.contactPerson', selected: true },
        // { key: 'extendedFields.contactWay', labelKey: 'purchaser.field.contactWay', selected: true },
        { key: 'phone', labelKey: 'purchaser.field.phone', selected: true },
        { key: 'fax', labelKey: 'purchaser.field.fax', selected: false },
        { key: 'address', labelKey: 'purchaser.field.address', selected: true },
        { key: 'extendedFields.zipCode', labelKey: 'purchaser.field.zipCode', selected: false },
        { key: 'email', labelKey: 'purchaser.field.email', selected: true },
        { key: 'website', labelKey: 'purchaser.field.website', selected: true },
        { key: 'extendedFields.sessionInfo', labelKey: 'purchaser.field.sessionInfo', selected: true }
      ];
    };

    const allFields = ref(createFieldsConfig());

    // 字段选择相关函数
    const initSelectedFields = () => {
      selectedFields.value = allFields.value.filter(field => field.selected).map(field => field.key);
    };

    const updateSelectedFields = () => {
      selectedFields.value = allFields.value.filter(field => field.selected).map(field => field.key);
    };

    const selectAllFields = () => {
      allFields.value.forEach(field => {
        field.selected = true;
      });
      updateSelectedFields();
    };

    const selectNoFields = () => {
      allFields.value.forEach(field => {
        field.selected = false;
      });
      updateSelectedFields();
    };

    const isAllFieldsSelected = computed(() => {
      return allFields.value.every(field => field.selected);
    });

    const isNoFieldsSelected = computed(() => {
      return allFields.value.every(field => !field.selected);
    });
    
    // 直接使用后端分页，不再需要前端分页
    const paginatedPurchasers = computed(() => purchasers.value)
    
    // 获取采购商数据
    const fetchPurchasers = async () => {
      loading.value = true
      try {
        const params = {
          keyword: searchKeyword.value,
          productType: productTypeKeyword.value, // 添加产品类型搜索参数
          page: currentPage.value,
          size: pageSize.value
        }
        // 添加筛选条件
        if (filters.contact && filters.contact.length > 0) {
          params.hasContact = filters.contact.join(',');
        }

        if (filters.sessionInfo.length > 0) {
          // 从广交会届数提取数字部分，例如"第127届广交会" -> "127"
          // 或者从英文格式提取，例如"Canton Fair 127th Session" -> "127"
          const sessionNumbers = filters.sessionInfo.map(session => {
            const match = session.match(/\d+/);
            return match ? match[0] : null;
          }).filter(Boolean);
          
          if (sessionNumbers.length > 0) {
            params.sessionInfo = sessionNumbers.join(',');
          }
        }
        
        if (filters.country.length > 0) {
          // 获取当前语言
          const currentLang = getCurrentLanguage();
          
          // 将选中的国家名称转换为后端需要的格式
          let selectedCountries = [...filters.country];
          
          // 如果当前是英文，需要将英文国家名称转换回原始格式
          if (currentLang === 'en') {
            selectedCountries = selectedCountries.map(country => {
              // 如果是英文国家名，尝试转换回原始格式（可能是中文或英文）
              return REVERSE_COUNTRY_TRANSLATIONS[country] || country;
            });
          }
          
          params.country = selectedCountries.join(',');
        }
        
        const response = await getCantonFairPurchasers(params)
        if (response.code === 200) {
          // 新的数据格式处理
          if (response.data && response.data.records && Array.isArray(response.data.records)) {
            // 处理采购商数据，将extendedFields中的字段展开到顶级
            purchasers.value = response.data.records.map(item => {
              const purchaser = { ...item, expanded: false };
              // 如果存在extendedFields，将其中的字段提取到顶层
              if (item.extendedFields && typeof item.extendedFields === 'object') {
                Object.keys(item.extendedFields).forEach(key => {
                  purchaser[key] = item.extendedFields[key];
                });
              }
              return purchaser;
            });
            
            // 从响应中获取分页信息，限制最大显示为10000
            total.value = Math.min(response.data.total || 0, 10000);
            // 确保total至少为1，避免分页控件不显示
            if (total.value <= 0 && purchasers.value.length > 0) {
              total.value = Math.min(purchasers.value.length, 10000);
            }
            currentPage.value = response.data.current || 1;
            pageSize.value = response.data.size || 10;
            
            if (purchasers.value.length === 0 && total.value > 0) {
              if (getCurrentLanguage() === 'zh'){
                ElMessage.warning('当前页无数据')
              }else {
                ElMessage.warning('No data found on this page')
              }
            } else if (purchasers.value.length === 0) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.warning('暂无数据')
              } else {
                ElMessage.warning('No data found')
              }
            }
          } else if (response.data && Array.isArray(response.data)) {
            // 兼容旧的数据格式（直接是数组）
            purchasers.value = response.data.map(item => ({
              ...item,
              ...(item.extendedFields || {}),
              expanded: false
            }));
            total.value = Math.min(response.total || response.data.length || 0, 10000);
            // 确保total至少为1，避免分页控件不显示
            if (total.value <= 0 && purchasers.value.length > 0) {
              total.value = Math.min(purchasers.value.length, 10000);
            }
            
            if (purchasers.value.length === 0) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.warning('暂无数据')
              } else {
                ElMessage.warning('No data found')
              }
            }
          } else {
            purchasers.value = []
            total.value = 0
            if (getCurrentLanguage() === 'zh') {
              ElMessage.warning('暂无数据')
            } else {
              ElMessage.warning('No data found')
            }
          }
        } else {
          purchasers.value = []
          total.value = 1 // 设置为1确保分页控件显示
          // 处理特定的业务错误码
          if (response.code === 500 && response.msg && response.msg.includes('余额不足')) {
            // 特殊处理余额不足的错误
            if (getCurrentLanguage() === 'zh'){
              ElMessage.error(response.msg);
            } else {
              ElMessage.error('Insufficient balance, please recharge');
            }
          } else {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(response.msg || '获取数据失败')
            } else {
              ElMessage.error('Failed to get data')
            }
          }
        }
      } catch (error) {
        purchasers.value = []
        total.value = 1 // 设置为1确保分页控件显示
        
        // 增强错误处理逻辑，确保能显示后端返回的具体错误信息
        if (error.response && error.response.data) {
          // 如果有响应数据，优先使用响应中的错误信息
          const errorData = error.response.data
          // 特殊处理余额不足的错误
          if (errorData.msg && errorData.msg.includes('余额不足')) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(errorData.msg);
            }else {
              ElMessage.error('Insufficient balance, please recharge');
            }
          } else {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(errorData.msg || errorData.message || '获取数据失败，请稍后重试')
            } else {
              ElMessage.error('Failed to get data, please try again later')
            }
          }
        } else if (error.data && (error.data.msg || error.data.message)) {
          // 有些情况下错误信息在error.data中
          // 特殊处理余额不足的错误
          if (error.data.msg && error.data.msg.includes('余额不足')) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(error.data.msg);
            }else {
              ElMessage.error('Insufficient balance, please recharge');
            }
          } else {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(error.data.msg || error.data.message)
            } else {
              ElMessage.error("Failed to get data, please try again later")
            }
          }
        } else if (error.msg || error.message) {
          // 直接在error对象上的错误信息
          // 特殊处理余额不足的错误
          const errorMsg = error.msg || error.message;
          if (errorMsg && errorMsg.includes && errorMsg.includes('余额不足')) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(errorMsg);
            }else {
              ElMessage.error('Insufficient balance, please recharge');
            }
          } else {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(errorMsg)
            } else {
              ElMessage.error("Failed to get data, please try again later")
            }
          }
        } else {
          // 默认错误信息
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('获取数据失败，请稍后重试')
          } else {
            ElMessage.error('Failed to get data, please try again later')
          }
        }
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchPurchasers()
    }
    
    // 重置名称/届数搜索
    const resetNameSearch = () => {
      searchKeyword.value = ''
      currentPage.value = 1
      fetchPurchasers()
    }
    
    // 重置产品类型搜索
    const resetProductTypeSearch = () => {
      productTypeKeyword.value = ''
      currentPage.value = 1
      fetchPurchasers()
    }
    
    // 重置所有搜索
    const resetSearch = () => {
      searchKeyword.value = ''
      productTypeKeyword.value = ''
      currentPage.value = 1
      fetchPurchasers()
    }
    
    // 切换采购商详情显示
    const togglePurchaserDetails = (purchaser) => {
      // 如果要展开当前项，先关闭其他已展开的项
      if (!purchaser.expanded) {
        paginatedPurchasers.value.forEach(item => {
          if (item !== purchaser && item.expanded) {
            item.expanded = false
          }
        })
      }
      purchaser.expanded = !purchaser.expanded
    }
    
    // 分页事件处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchPurchasers()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchPurchasers()
    }
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        // 先获取符合条件的记录数量
        await fetchExportCount()
        
        // 再获取用户余额
        await fetchUserBalance()
        
        // 显示导出对话框
        exportDialogVisible.value = true
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('准备导出失败，请稍后重试')
        } else {
          ElMessage.error('Failed to prepare export, please try again later')
        }
      } finally {
        exportLoading.value = false
      }
    }
    
    // 获取符合条件的记录数量
    const fetchExportCount = async () => {
      try {
        // 构建查询参数
        const params = {};
        
        // 添加搜索关键词
        if (searchKeyword.value) {
          params.keyword = searchKeyword.value;
        }
        
        // 添加产品类型搜索参数
        if (productTypeKeyword.value) {
          params.productType = productTypeKeyword.value;
        }
        
        // 添加筛选条件
        if (filters.sessionInfo.length > 0) {
          // 从广交会届数提取数字部分，例如"第127届广交会" -> "127"
          // 或者从英文格式提取，例如"Canton Fair 127th Session" -> "127"
          const sessionNumbers = filters.sessionInfo.map(session => {
            const match = session.match(/\d+/);
            return match ? match[0] : null;
          }).filter(Boolean);
          
          if (sessionNumbers.length > 0) {
            params.sessionInfo = sessionNumbers.join(',');
          }
        }
        
        if (filters.country.length > 0) {
          // 获取当前语言
          const currentLang = getCurrentLanguage();
          
          // 将选中的国家名称转换为后端需要的格式
          let selectedCountries = [...filters.country];
          
          // 如果当前是英文，需要将英文国家名称转换回原始格式
          if (currentLang === 'en') {
            selectedCountries = selectedCountries.map(country => {
              // 如果是英文国家名，尝试转换回原始格式（可能是中文或英文）
              return REVERSE_COUNTRY_TRANSLATIONS[country] || country;
            });
          }
          
          params.country = selectedCountries.join(',');
        }

        if (filters.contact && filters.contact.length > 0){
          params.hasContact = filters.contact.join(',');
        }
        
        // 获取符合条件的记录数量
        const response = await getCantonFairPurchasersCount(params);
        
        if (response.code === 200) {
          // 从响应中提取count字段
          const count = response.data.count || 0;
          
          // 限制导出的最大记录数为50000
          totalMatchCount.value = Math.min(count, 50000);
          exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
          return count;
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(response.msg || '获取记录数量失败');
          } else {
            ElMessage.error('Failed to get record count');
          }
          return 0;
        }
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('获取记录数量失败，请稍后重试');
        } else {
          ElMessage.error('Failed to get record count, please try again later');
        }
        return 0;
      }
    }
    
    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const response = await getUserBalanceInfo();
        if (response.code === 200 && response.data) {
          userBalance.value = response.data;
          return response.data;
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(response.msg || '获取余额信息失败');
          } else {
            ElMessage.error('Failed to get balance info');
          }
          return { exportQuotaRemaining: 0 };
        }
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('获取余额信息失败，请稍后重试');
        } else {
          ElMessage.error('Failed to get balance info');
        }
        return { exportQuotaRemaining: 0 };
      }
    }
    
    // 执行导出操作
    const doExport = async () => {
      // 检查字段选择
      if (isNoFieldsSelected.value) {
        ElMessage.error(t('export.error.noFieldsSelected'));
        return;
      }
      
      // 检查导出数量
      if (isExportCountExceeded.value) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`导出数量不能超过符合条件的记录数 ${totalMatchCount.value}`);
        } else {
          ElMessage.error(`Export count cannot exceed the total number of records that meet the conditions ${totalMatchCount.value}`);
        }
        return;
      }
      
      // 检查导出上限
      if (isExportLimitExceeded.value) {
        if (getCurrentLanguage() === 'zh') {
        ElMessage.error('导出数量不能超过50000条');
        } else {
          ElMessage.error('Export count cannot exceed 50000')
        }
        return;
      }
      
      // 检查余额
      if (isBalanceInsufficient.value) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`导出余额不足，当前余额: ${userBalance.value.exportQuotaRemaining}`);
        }else {
          ElMessage.error(`Insufficient export balance, current balance: ${userBalance.value.exportQuotaRemaining}`);
        }
        return;
      }
      
      // 确保导出数量是有效的数字
      if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('请输入有效的导出数量');
        } else {
          ElMessage.error('Please enter a valid export count');
        }
        return;
      }

    

      // 检查字段选择
      if (selectedFields.value.length === 0) {
        ElMessage.error(t('export.error.noFieldsSelected'));
        return;
      }

      exportLoading.value = true;
      exportDialogVisible.value = false;
      
      // 如果导出数量大于10000，显示特殊提示
      if (exportCount.value > 10000) {
        ElMessage({
          message: t('export.warning.largeData'),
          type: 'info',
          duration: 10000
        });
      } else {
        ElMessage({
          message: t('export.info.exporting'),
          type: 'info',
          duration: 5000
        });
      }
      
      try {
        // 准备导出参数对象
        const exportParams = {
          exportCount: Number(exportCount.value), // 确保转换为数字类型
          selectedFields: selectedFields.value.join(','), // 添加选中的字段列表
          language: currentLanguage.value // 添加当前语言参数
        };

        // 添加搜索关键词
        if (searchKeyword.value) {
          exportParams.keyword = searchKeyword.value;
        }
        
        // 添加产品类型搜索参数
        if (productTypeKeyword.value) {
          exportParams.productType = productTypeKeyword.value;
        }
        
        // 添加筛选条件
        if (filters.sessionInfo.length > 0) {
          // 从广交会届数提取数字部分，例如"第127届广交会" -> "127"
          // 或者从英文格式提取，例如"Canton Fair 127th Session" -> "127"
          const sessionNumbers = filters.sessionInfo.map(session => {
            const match = session.match(/\d+/);
            return match ? match[0] : null;
          }).filter(Boolean);
          
          if (sessionNumbers.length > 0) {
            exportParams.sessionInfo = sessionNumbers.join(',');
          }
        }
        
        if (filters.country.length > 0) {
          // 获取当前语言
          const currentLang = getCurrentLanguage();
          
          // 将选中的国家名称转换为后端需要的格式
          let selectedCountries = [...filters.country];
          
          // 如果当前是英文，需要将英文国家名称转换回原始格式
          if (currentLang === 'en') {
            selectedCountries = selectedCountries.map(country => {
              // 如果是英文国家名，尝试转换回原始格式（可能是中文或英文）
              return REVERSE_COUNTRY_TRANSLATIONS[country] || country;
            });
          }
          
          // 以逗号分隔的字符串传递给后端（与查询与计数接口保持一致）
          exportParams.country = selectedCountries.join(',');
        }

        if (filters.contact && filters.contact.length > 0){
          exportParams.hasContact = filters.contact.join(',');
        }
        
        // 发送请求
        const response = await exportCantonFairPurchasers(exportParams);
        // 检查响应是否为blob
        if (!response || !response.data) {
          if (getCurrentLanguage() === 'zh') {
            throw new Error('导出失败：服务器未返回数据');
          } else {
            throw new Error('Export failed: server did not return data');
          }
        }
        
        if (!(response.data instanceof Blob)) {
          if (getCurrentLanguage() === 'zh') {
            throw new Error('导出失败：服务器返回格式不正确');
          } else {
            throw new Error('Export failed: server returned data in an incorrect format');
          }
        }
        
        // 获取Content-Type
        const contentType = response.headers && response.headers['content-type'] 
          ? response.headers['content-type'] 
          : 'application/vnd.ms-excel'
        
        // 检查是否是错误响应
        if (contentType.includes('json')) {
          // 可能是错误响应，尝试解析
          const reader = new FileReader();
          
          // 使用Promise包装FileReader
          const readJsonResponse = new Promise((resolve, reject) => {
            reader.onload = function() {
              try {
                const result = reader.result;
                const errorResponse = JSON.parse(result);
                resolve(errorResponse);
              } catch (e) {
                if (getCurrentLanguage() === 'zh'){
                  reject(new Error('导出失败：无法识别的错误'));
                } else {
                  reject(new Error('Export failed: unable to recognize error'));
                }
              }
            };
            reader.onerror = function(e) {
              if (getCurrentLanguage() === 'zh') {
                reject(new Error('导出失败：无法读取错误响应'));
              } else {
                reject(new Error('Export failed: unable to read error response'));
              }
            };
          });
          
          reader.readAsText(response.data);
          
          try {
            const errorData = await readJsonResponse;
            // 显示具体的错误信息
            const errorMessage = errorData.msg || errorData.message || '未知错误';
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(`导出失败：${errorMessage}`);
            } else {
              ElMessage.error(`Export failed`);
            }

            // 如果错误与参数相关，可能需要提示用户修改导出数量
            if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.warning('请检查导出数量是否正确设置');
              } else {
                ElMessage.warning('Please check if the export count is set correctly');
              }
            }
            return;
          } catch (e) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(e.message || '导出失败');
            } else {
              ElMessage.error('Export failed')
            }
            return;
          }
        }
        
        // 创建Blob对象
        const blob = new Blob([response.data], { type: contentType })
        
        // 获取文件名
        let fileName = '广交会采购商数据.xlsx'
        const disposition = response.headers && response.headers['content-disposition']
        if (disposition && disposition.includes('filename=')) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
          const matches = filenameRegex.exec(disposition)
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '')
            try {
              fileName = decodeURIComponent(fileName)
            } catch (e) {
            }
          }
        }
        
        // 下载文件
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        // 关闭导出对话框
        exportDialogVisible.value = false
        
        // 更新用户余额
        await fetchUserBalance()

        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('导出成功')
        } else {
          ElMessage.success('Export successful')
        }
      } catch (error) {
        // 处理超时错误
        if (error.message && error.message.includes('timeout')) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('导出请求超时，数据量可能过大，请减少导出数量或稍后再试');
          } else {
            ElMessage.error('Export request timed out, the amount of data may be too large, please reduce the export count or try again later');
          }
          return;
        }
        
        // 尝试从错误响应中解析错误信息
        let errorMsg = '导出失败，请稍后重试';
        if (error.response && error.response.data) {
          try {
            // 尝试解析blob数据为JSON
            if (error.response.data instanceof Blob) {
              const text = await error.response.data.text();
              try {
                const jsonResponse = JSON.parse(text);
                errorMsg = jsonResponse.msg || jsonResponse.message || '导出失败，服务器返回错误';
              } catch (parseError) {
              }
            }
          } catch (parseError) {
          }
        }
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(errorMsg);
        } else {
          ElMessage.error('Export failed, please try again later');
        }
      } finally {
        exportLoading.value = false
      }
    }
    
    // 为URL添加http前缀（如果没有）
    const addHttpPrefix = (url) => {
      if (!url) return ''
      return url.startsWith('http') ? url : 'http://' + url
    }
    
    // 获取国旗图标
    const getCountryFlag = (country) => {
      if (!country) return ''
      const countryMapping = {
        '中国': 'cn', '美国': 'us', '日本': 'jp', '英国': 'gb',
        '德国': 'de', '法国': 'fr', '加拿大': 'ca', '澳大利亚': 'au',
        '印度': 'in', '巴西': 'br', '俄罗斯': 'ru', '韩国': 'kr',
        '意大利': 'it', '西班牙': 'es', '墨西哥': 'mx', '印度尼西亚': 'id',
        '荷兰': 'nl', '沙特阿拉伯': 'sa', '瑞士': 'ch', '土耳其': 'tr',
        '台湾': 'tw', '瑞典': 'se', '波兰': 'pl', '比利时': 'be',
        '泰国': 'th', '爱尔兰': 'ie', '奥地利': 'at', '挪威': 'no',
        '阿联酋': 'ae', '以色列': 'il', '丹麦': 'dk', '新加坡': 'sg',
        '马来西亚': 'my', '香港': 'hk', '菲律宾': 'ph', '越南': 'vn',
        '孟加拉国': 'bd', '伊朗': 'ir'
      }
      
      let code = countryMapping[country]
      if (!code) {
        for (const [key, value] of Object.entries(countryMapping)) {
          if (country.includes(key)) {
            code = value
            break
          }
        }
      }
      
      return code ? `https://flagcdn.com/16x12/${code.toLowerCase()}.png` : ''
    }
    
    // 处理国旗加载错误
    const handleFlagError = (e) => {
      e.target.style.display = 'none'
    }
    
    // 获取卡通头像URL
    const getAvatarUrl = (name) => {
      if (!name) return 'https://api.dicebear.com/7.x/bottts/svg?seed=fallback'
      const seed = encodeURIComponent(name)
      return `https://api.dicebear.com/7.x/bottts/svg?seed=${seed}`
    }
    
    // 处理头像加载错误
    const handleAvatarError = (e) => {
      e.target.src = 'https://api.dicebear.com/7.x/bottts/svg?seed=fallback'
    }
    
    // 获取其他扩展字段（排除已经显示的字段）
    const getOtherExtendedFields = (purchaser) => {
      const excludedFields = [
        'id', 'companyName', 'country', 'contactPerson', 'phone', 'fax', 
        'address', 'email', 'expanded', 'sessionInfo', 'countryRegion', 
        'procurementProductType', 'contactTeam', 'zipCode', 'webAddress', 'website', 'extendedFields',
        'sessionsNum', // 添加sessionsNum以隐藏Sessions Num: 127字段
        'sessionNum',  // 添加单数形式
        'session',     // 添加简单形式
        'sessionNo',   // 添加另一种可能的命名
        'sessionNumber' // 添加完整命名
      ];
      
      const result = {};
      Object.keys(purchaser).forEach(key => {
        if (!excludedFields.includes(key) && purchaser[key]) {
          result[key] = purchaser[key];
        }
      });
      
      return result;
    }
    
    // 格式化字段名称
    const formatFieldName = (key) => {
      // 将驼峰命名转换为中文显示
      const nameMapping = {
        'sessionInfo': '广交会届数',
        'countryRegion': '国家/地区',
        'procurementProductType': '采购产品类型',
        'contactPerson': '联系人',
        'contactWay': '联系方式',
        'phone': '电话',
        'fax': '传真',
        'address': '地址',
        'email': '邮箱',
        // 'webAddress': '网站',
        'website': '网站',
        'zipCode': '邮编',
        'extendedFields': '扩展字段',
        'productCategories': '产品类别',
        'companyIntroduction': '公司介绍',
        'purchaseIntention': '采购意向',
        'attendanceHistory': '参会历史',
        // 添加session相关字段的映射，但这些字段已经在excludedFields中排除了
        'sessionsNum': '广交会届数',
        'sessionNum': '广交会届数',
        'session': '广交会届数',
        'sessionNo': '广交会届数',
        'sessionNumber': '广交会届数'
      };
      
      if (nameMapping[key]) {
        return nameMapping[key];
      }
      
      // 处理驼峰命名
      if (/[A-Z]/.test(key)) {
        return key
          .replace(/([A-Z])/g, ' $1')
          .replace(/^./, str => str.toUpperCase())
          .trim();
      }
      
      return key;
    }

    // 字段显示名称（含i18n）：优先识别mobile与公司概况
    const getFieldLabel = (key) => {
      if (!key) return ''
      const lower = String(key).toLowerCase().trim()
      // mobile
      if (lower === 'mobile') {
        return t('canton.purchaser.mobile') + ':'
      }
      if (lower === 'purchaselist') {
        return t('canton.purchaser.purchaseList') + ':'
      }
      if (lower === 'demandinfo') {
        return t('canton.purchaser.demandInfo') + ':'
      }
      // company profile 相关键
      const companyKeys = new Set([
        'companyprofile',
        'company profile',
        'companyprofilehtml',
        'company introduction',
        'companyProfile'
      ])
      if (companyKeys.has(lower)) {
        return t('canton.purchaser.companyProfile') + ':'
      }
      // 兼容包含短语
      if (lower.includes('company') && lower.includes('profile')) {
        return t('canton.purchaser.companyProfile') + ':'
      }
      // 回退到原有格式化
      return formatFieldName(key) + ':'
    }

    // 是否以HTML渲染该字段（仅公司概况）
    const shouldRenderHtml = (key, value) => {
      if (!key) return false
      const lower = String(key).toLowerCase().trim()
      if (
        lower === 'companyprofile' ||
        lower === 'company profile' ||
        lower === 'companyprofilehtml' ||
        lower === 'company introduction' ||
        lower === 'companyintroduction'
      ) {
        return true
      }
      return false
    }

    // 规范化字段键名（如 Mobile/mObIlE -> mobile）
    const normalizeFieldKey = (key) => {
      if (!key) return ''
      const lower = String(key).toLowerCase().trim()
      if (lower === 'mobile' || lower === 'cellphone' || lower === 'cell' || lower === 'mobilephone') return 'mobile'
      return lower
    }

    // 判断动态扩展字段是否需要遮罩点击（目前针对 mobile）
    const isMaskedInfo = (key, value) => {
      const lower = normalizeFieldKey(key)
      if (lower === 'mobile' && typeof value === 'string' && value.includes('*')) {
        return true
      }
      return false
    }

    // 处理电话、传真和邮箱的点击事件
    const showFullContactInfo = async (purchaser, field) => {
      // 只有当信息包含星号时才需要查询完整信息
      if (!(purchaser[field] && purchaser[field].includes('*'))) {
        return;
      }
      
      try {
        // 弹出确认对话框
        await ElMessageBox.confirm(
          t('canton.purchaser.confirm.view.contact'),
          t('canton.purchaser.view.full.contact'),
          {
            confirmButtonText: t('canton.purchaser.confirm'),
            cancelButtonText: t('canton.purchaser.cancel'),
            type: 'warning'
          }
        );
        
        // 获取sessionInfo，优先使用purchaser.sessionInfo，如果没有则使用筛选中选择的会话
        const sessionInfo = purchaser.sessionInfo || (filters.sessionInfo.length === 1 ? filters.sessionInfo[0] : '');

        // 从sessionInfo中提取届数数字
        let sessionNumber = '';
        if (sessionInfo) {
          const match = sessionInfo.match(/\d+/);
          sessionNumber = match ? match[0] : '';
        }
        
        if (!sessionNumber) {
          ElMessage.error(t('canton.purchaser.session.required'));
          return;
        }
        
        // 用户点击确认，调用API获取完整信息
        const response = await getPurchaserFullContactInfo(purchaser.id, sessionNumber, field);
        
        if (response.code === 200 && response.data) {
          // 更新当前采购商的联系信息
          if (response.data[field]) {
            // 直接使用返回的字段值更新对应字段
            purchaser[field] = response.data[field];
          }
          
          ElMessage.success(t('canton.purchaser.contact.view.success'));
        } else {
          ElMessage.error(response.msg || t('canton.purchaser.contact.view.error'));
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 处理特定错误，如余额不足
          if (error.response && error.response.data && error.response.data.msg) {
            ElMessage.error(error.response.data.msg);
          } else {
            ElMessage.error(t('canton.purchaser.contact.view.error'));
          }
        }
      }
    }
    
    onMounted(() => {
      // 添加新的翻译键
      addTranslation('canton.purchaser.filter.contact', {
        zh: '联系方式',
        en: 'Contact Methods'
      });

      addTranslation('canton.purchaser.filter.contact.phone', {
        zh: '电话',
        en: 'Phone'
      });

      addTranslation('canton.purchaser.filter.contact.fax', {
        zh: '传真',
        en: 'Fax'
      });

      addTranslation('canton.purchaser.filter.contact.email', {
        zh: '邮箱',
        en: 'Email'
      });

      addTranslation('canton.purchaser.filter.contact.website', {
        zh: '网站',
        en: 'Website'
      });

      addTranslation('canton.purchaser.matching.records', {
        zh: '符合条件的企业数量',
        en: 'Matching enterprises'
      });

      // 添加查看联系信息相关翻译
      addTranslation('canton.purchaser.view.full.contact.tooltip', {
        zh: '点击消耗一次次数查看完整信息',
        en: 'Click to view full information (costs 1 credit)'
      });
      
      // 添加搜索相关翻译
      addTranslation('canton.purchaser.search.name.session.label', {
        zh: '采购商名称/届数',
        en: 'Buyer Name/Session'
      });
      
      addTranslation('canton.purchaser.search.name.session.placeholder', {
        zh: '输入采购商名称或广交会届数',
        en: 'Enter buyer name or canton fair session'
      });
      
      addTranslation('canton.purchaser.search.product.type.label', {
        zh: '采购产品类型',
        en: 'Product Type'
      });
      
      addTranslation('canton.purchaser.search.product.type.placeholder', {
        zh: '输入采购产品类型',
        en: 'Enter product type to search'
      });
      
      addTranslation('canton.purchaser.search.button', {
        zh: '搜索',
        en: 'Search'
      });

      // 初始化选中的字段
      initSelectedFields();

      // 添加导出相关翻译
      addTranslation('export.dialog.title', {
        zh: '导出数据',
        en: 'Export Data'
      });

      addTranslation('export.matching.records', {
        zh: '符合条件的记录数',
        en: 'Matching records'
      });

      addTranslation('export.current.balance', {
        zh: '当前导出余额',
        en: 'Current export balance'
      });

      addTranslation('export.note', {
        zh: '注意: 每导出一条记录将消耗一点导出额度',
        en: 'Note: Each exported record will consume one export credit'
      });

      addTranslation('export.enter.count', {
        zh: '请输入要导出的记录数:',
        en: 'Please enter the number of records to export:'
      });

      addTranslation('export.cancel', {
        zh: '取消',
        en: 'Cancel'
      });

      addTranslation('export.confirm', {
        zh: '确认导出',
        en: 'Confirm Export'
      });

      addTranslation('export.warning.exceed', {
        zh: '导出数量不能超过符合条件的记录数',
        en: 'Export quantity cannot exceed the number of matching records'
      });

      addTranslation('export.warning.balance', {
        zh: '导出余额不足',
        en: 'Insufficient export balance'
      });

      addTranslation('export.warning.limit', {
        zh: '导出数量不能超过50000条',
        en: 'Export quantity cannot exceed 50,000 records'
      });

      addTranslation('canton.purchaser.confirm.view.contact', {
        zh: '查看完整联系信息将消耗一次查看次数，是否继续？',
        en: 'Viewing full contact information will cost 1 credit. Continue?'
      });
      
      addTranslation('canton.purchaser.view.full.contact', {
        zh: '查看完整联系信息',
        en: 'View Full Contact Information'
      });
      
      addTranslation('canton.purchaser.confirm', {
        zh: '确认',
        en: 'Confirm'
      });
      
      addTranslation('canton.purchaser.cancel', {
        zh: '取消',
        en: 'Cancel'
      });
      
      addTranslation('canton.purchaser.contact.view.success', {
        zh: '联系信息获取成功',
        en: 'Contact information retrieved successfully'
      });
      
      addTranslation('canton.purchaser.contact.view.error', {
        zh: '获取联系信息失败，请稍后重试',
        en: 'Failed to retrieve contact information, please try again later'
      });
      
      addTranslation('canton.purchaser.session.required', {
        zh: '无法确定广交会届数，请选择一个届数后重试',
        en: 'Cannot determine Canton Fair session, please select a session and try again'
      });

      addTranslation('export.max.limit.notice', {
        zh: '单次最多导出50000条数据',
        en: 'Maximum 50,000 records per export'
      });
      
      addTranslation('export.error.noFieldsSelected', {
        zh: '请至少选择一个导出字段',
        en: 'Please select at least one field to export'
      });
      
      addTranslation('export.selectFields', {
        zh: '请选择要导出的字段',
        en: 'Select fields to export'
      });
      
      addTranslation('export.selectAll', {
        zh: '全选',
        en: 'Select All'
      });
      
      addTranslation('export.selectNone', {
        zh: '清空',
        en: 'Clear All'
      });
      
      addTranslation('export.noFieldsSelected', {
        zh: '请至少选择一个字段',
        en: 'Please select at least one field'
      });

      // 新增：移动电话与公司概况字段标签
      addTranslation('canton.purchaser.mobile', {
        zh: '手机',
        en: 'Mobile'
      })
      addTranslation('canton.purchaser.companyProfile', {
        zh: '公司概况',
        en: 'Company Profile'
      })

      fetchPurchasers()
    })
    
    return {
      loading,
      exportLoading,
      purchasers,
      searchKeyword,
      productTypeKeyword,
      currentPage,
      pageSize,
      total,
      paginatedPurchasers,
      fetchPurchasers,
      handleSearch,
      resetSearch,
      resetNameSearch,
      resetProductTypeSearch,
      togglePurchaserDetails,
      handleSizeChange,
      handleCurrentChange,
      exportData,
      addHttpPrefix,
      getCountryFlag,
      handleFlagError,
      getAvatarUrl,
      handleAvatarError,
      getOtherExtendedFields,
      formatFieldName,
      getFieldLabel,
      shouldRenderHtml,
      isMaskedInfo,
      normalizeFieldKey,
      // 添加查看完整联系信息函数
      showFullContactInfo,
      // 导出相关
      exportDialogVisible,
      totalMatchCount,
      exportCount,
      userBalance,
      isExportCountExceeded,
      isBalanceInsufficient,
      isExportLimitExceeded,
      fetchExportCount,
      fetchUserBalance,
      doExport,
      // 字段选择相关
      selectedFields,
      allFields,
      currentLanguage,
      initSelectedFields,
      updateSelectedFields,
      selectAllFields,
      selectNoFields,
      isAllFieldsSelected,
      isNoFieldsSelected,
      // 筛选相关
      expanded,
      filters,
      checkAll,
      isIndeterminate,
      sessionInfoSearch,
      countrySearch,
      filteredSessionInfos: localizedSessionInfos,
      filteredCountries: localizedCountries,
      toggleFilter,
      handleCheckAllChange,
      handleFilterChange,
      handleContactChange,
      resetAllFilters,
      getOptionsForField,
      // 添加t函数
      t,
      // 添加获取当前语言的函数
      getCurrentLanguage,
      COUNTRY_TRANSLATIONS,
      REVERSE_COUNTRY_TRANSLATIONS
    }
  }
}
</script>

<style scoped>
.canton-fair-purchasers-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.main-container {
  display: flex;
  min-height: calc(100vh - 60px);
  position: relative;
  flex: 1;
  height: 100%;
  overflow: hidden; /* 防止页面级滚动，只让内容区滚动 */
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto; /* 只滚动右侧内容区 */
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.search-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.search-box-container {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.search-fields-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  width: 100%;
  margin-bottom: 15px;
}

.search-field {
  flex: 1;
  min-width: 280px;
}

.search-field-label {
  font-size: 14px;
  margin-bottom: 5px;
  text-align: left;
  color: #606266;
}

.search-input {
  width: 100%;
  font-size: 16px;
}

.search-input :deep(.el-input__inner) {
  font-size: 16px;
  height: 40px;
  text-align: center;
}

.search-input :deep(.el-input__inner::placeholder) {
  text-align: center;
}

.search-button {
  width: 120px;
  height: 40px;
  font-size: 16px;
}

/* 主内容区域样式 */
.purchasers-main {
  display: flex;
  gap: 20px;
  flex: 1;
}

/* 左侧筛选器样式 */
.filter-sidebar-container {
  width: 280px;
  flex-shrink: 0;
  position: relative;
}

.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.reset-filter-container {
  margin-bottom: 15px;
  text-align: center;
}

.reset-filter-btn {
  width: 100%;
}

/* 筛选组样式 */
.filter-group {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.filter-group.expanded {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.filter-content {
  padding: 15px;
  max-height: 250px;
  overflow-y: auto;
}

/* 筛选器内搜索框 */
.filter-search {
  margin-bottom: 10px;
}

.el-icon {
  transition: transform 0.3s ease;
}

.el-icon-arrow-up {
  transform: rotate(180deg);
}

.el-icon-arrow-down {
  transform: rotate(0deg);
}

/* 右侧数据内容样式 */
.data-content {
  flex: 1;
  padding: 20px;
  overflow-x: hidden; /* 避免双滚动条，由 .content 负责纵向滚动 */
}

/* 导出模块样式 */
.export-module {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.export-info {
  font-size: 14px;
  color: #606266;
}

.export-count {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin-left: 5px;
}

.export-module-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background-color: #409eff;
  border-color: #409eff;
  padding: 10px 20px;
}

/* 采购商卡片样式 */
.purchaser-card-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.purchaser-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
}

.purchaser-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.company-info {
  display: flex;
  align-items: center;
  gap: 15px;
  width: 100%;
}

.company-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background-color: #f5f7fa;
}

.cartoon-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.company-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  word-break: break-word;
}

.card-divider {
  height: 1px;
  background-color: #eaeaea;
  margin: 15px 0;
  width: 100%;
}

.info-button-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-basic-info {
  flex: 1;
}

.detail-button-container {
  margin-left: 15px;
  display: flex;
  align-items: center;
  padding-top: 5px;
}

.detail-btn {
  padding: 6px 15px;
  font-size: 13px;
  background-color: #f0f9ff;
  color: #19B5FE;
  border: 1px solid #19B5FE;
  border-radius: 4px;
}

.detail-btn:hover {
  background-color: #e1f5fe;
}

/* 基本信息区域样式 */
.basic-info-grid {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.info-item {
  flex: 1;
  min-width: 140px;
}

.full-width {
  width: 100%;
}

.info-label {
  font-size: 13px;
  color: #666;
  margin-right: 5px;
}

.info-value {
  font-size: 13px;
  color: #333;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.country-flag {
  width: 16px;
  height: 12px;
  object-fit: cover;
  margin-right: 5px;
  border: 1px solid #eee;
}

/* 详细内容区域样式 */
.card-content {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.detail-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.info-table-wrapper {
  overflow-x: auto;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 6px 0;
  font-size: 13px;
  vertical-align: top;
}

.label-cell {
  color: #666;
  width: 15%;
  padding-right: 10px;
  white-space: nowrap;
}

.value-cell {
  color: #333;
  width: 85%;
  padding-right: 15px;
  word-break: break-all;
}

/* 无数据提示样式 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  text-align: center;
  color: #909399;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #e6a23c;
}

.no-data p {
  margin-bottom: 15px;
}

/* 骨架屏样式 */
.skeleton-loading {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.skeleton-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  animation: loading 1.5s infinite;
}

.skeleton-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.skeleton-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background-color: #f0f0f0;
}

.skeleton-title {
  flex: 1;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

.skeleton-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.skeleton-line {
  height: 15px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

@keyframes loading {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

/* 分页样式 */
.pagination-container {
  margin-top: 25px;
  margin-bottom: 25px;
  padding: 15px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.pagination-container :deep(.el-pagination) {
  font-weight: normal;
  justify-content: center;
  width: 100%;
}

.pagination-container :deep(.el-pagination .el-pagination__total) {
  font-weight: bold;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .search-fields-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-field {
    width: 100%;
    min-width: 100%;
  }
  
  .search-button {
    width: 100%;
    margin-top: 5px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .export-module {
    flex-direction: column;
    gap: 10px;
  }
  
  .export-module-btn {
    width: 100%;
  }
  
  .info-button-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .detail-button-container {
    margin-left: 0;
    width: 100%;
  }
  
  .detail-btn {
    width: 100%;
  }
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 字段选择区域样式 */
.field-selection-area {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.field-selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.field-selection-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.field-selection-actions {
  display: flex;
  gap: 8px;
}

.field-selection-content {
  margin-bottom: 15px;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.field-item {
  display: flex;
  align-items: center;
}

.field-checkbox {
  width: 100%;
}

.field-checkbox .el-checkbox__label {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.field-selection-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.selected-count {
  font-weight: 500;
}

/* 遮蔽的联系信息样式 */
.masked-info {
  color: #409eff;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  position: relative;
  padding-right: 20px;
}

.masked-info:hover {
  text-decoration: underline;
}

.info-lock-icon {
  font-size: 14px;
  margin-left: 5px;
  color: #909399;
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>